package com.payment.ktb.Fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.flyco.animation.Attention.Tada;
import com.flyco.dialog.widget.base.BaseDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.LoginActivity;
import com.payment.ktb.activity.ShowH5WithTitleActivity;
import com.payment.ktb.activity.main1.CashierActivity;
import com.payment.ktb.activity.main1.CashierUnionOnlineActivity;
import com.payment.ktb.activity.main1.MessageListActivity;
import com.payment.ktb.activity.main4.CardWrapActivity;
import com.payment.ktb.activity.main4.CardWrapEmptyActivity;
import com.payment.ktb.activity.main4.MembershipCenterActivity;
import com.payment.ktb.activity.main4.PlayVideoActivity;
import com.payment.ktb.adapter.AdapterFragment1Grid;
import com.payment.ktb.adapter.Main1BannerPagerAdapter;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.AdvertisementEntity;
import com.payment.ktb.model.IndexPageModelEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.LogUtil;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;
import com.payment.ktb.view.BadgeView;
import com.payment.ktb.view.MyGridView;
import com.payment.ktb.view.SecKillSuccessDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by syd on 2016/6/28.
 */
public class Fragment_main1 extends BaseFragment implements View.OnClickListener,ViewPager.OnPageChangeListener{

    int currentItem = 0;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
    SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH");
    SimpleDateFormat simpleDateFormatMinute = new SimpleDateFormat("mm");
    SimpleDateFormat simpleDateFormatSecond = new SimpleDateFormat("ss");
    ScheduledExecutorService mScheduledExecutorService = null;
    ScheduledExecutorService mSecKilScheduledExecutorService = null;
    View view = null;
    ViewPager vp_main1_banner;
    MyGridView mgv_main1;
    LinearLayout ll_main1_banner;
    Main1BannerPagerAdapter bannerPagerAdapter = null;
    List<AdvertisementEntity> bannersList = new ArrayList<AdvertisementEntity>();
    BadgeView badgeView;
    RelativeLayout rl_main1_message;
    TextView tv_main1_seckil_hour;
    TextView tv_main1_seckil_minutes;
    TextView tv_main1_seckil_second;
    LinearLayout ll_main1_grid_1_1;
    LinearLayout ll_main1_grid_1_2;
    LinearLayout ll_main1_grid_2_1;
    LinearLayout ll_main1_grid_2_2;
    TextView tv_main1_coupon_timedesc;
    TextView tv_main1_coupon_percent;
    TextView tv_main1_seckill_timenotes;
    Button btn_main1_coupon;
    ProgressBar pb_main1_coupon;
    int nowHour =  Integer.valueOf(simpleDateFormatHour.format(new Date()));
    String timestamp = String.valueOf(new Date().getTime());
    private int systemUnRead;
    private String systemLastMsgTime;
    private String systemLastMsg;
    private int activeUnRead;
    private String activeLastMsgTime;
    private String activeLastMsg;
    List<IndexPageModelEntity> listIndexPageModelEntities;
    private AdapterFragment1Grid mMain1BannerPagerAdapter;

    @Override
    public void onStart() {

        super.onStart();
        //用一个定时器  来完成图片切换
        //Timer 与 ScheduledExecutorService 实现定时器的效果
        mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        mSecKilScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //通过定时器 来完成 每2秒钟切换一个图片
        //经过指定的时间后，执行所指定的任务
        //scheduleAtFixedRate(command, initialDelay, period, unit)
        //command 所要执行的任务
        //initialDelay 第一次启动时 延迟启动时间
        //period  每间隔多次时间来重新启动任务
        //unit 时间单位
        mScheduledExecutorService.scheduleAtFixedRate(new ViewPagerTask(), 5, 5, TimeUnit.SECONDS);
        mSecKilScheduledExecutorService.scheduleAtFixedRate(new SecKilTask(), 0, 1, TimeUnit.SECONDS);


    }


    @Override
    public void onStop() {
        super.onStop();
        //停止图片切换
        if (mScheduledExecutorService != null) {
            mScheduledExecutorService.shutdown();
        }
        if (mSecKilScheduledExecutorService != null) {
            mSecKilScheduledExecutorService.shutdown();
        }


    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_main1,null);
        tv_main1_coupon_timedesc = (TextView) view.findViewById(R.id.tv_main1_coupon_timedesc);
        mgv_main1 = (MyGridView) view.findViewById(R.id.mgv_main1);
        mgv_main1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent ;

                switch (listIndexPageModelEntities.get(i).getUrl()) {

                    //jnlife开头的代表内部界面
                    //http开头的跳h5网页

                    //收银台
                    case "jnlife://syt":

                        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
                            intent = new Intent(mContext,CashierActivity.class);
                            startActivity(intent);
                        } else {
                            getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
                            getActivity().overridePendingTransition(R.anim.activity_open,0);
                        }
                        break;

                    //开通会员
                    case "jnlife://openvip":

                        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
                            getVipInfo();
                        } else {
                            getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
                            getActivity().overridePendingTransition(R.anim.activity_open,0);
                        }
                        break;


                    //银联快捷
                    case "jnlife://unionh5":

                        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
                            startActivity(CashierUnionOnlineActivity.class);
                        } else {
                            getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
                            getActivity().overridePendingTransition(R.anim.activity_open,0);
                        }
                        break;

                    default:
                        intent = new Intent(mContext,ShowH5WithTitleActivity.class);
                        intent.putExtra("title",listIndexPageModelEntities.get(i).getTitle());
                        intent.putExtra("url",listIndexPageModelEntities.get(i).getUrl());
                        startActivity(intent);
                        break;

                }
            }
        });
        tv_main1_coupon_timedesc.setText("每天" + Constants.SECKILLSTART  + "点、" + Constants.SECKILLMIDDLE + "点准时开抢");
        tv_main1_coupon_percent = (TextView) view.findViewById(R.id.tv_main1_coupon_percent);
        tv_main1_seckil_hour = (TextView) view.findViewById(R.id.tv_main1_seckil_hour);
        tv_main1_seckil_minutes = (TextView) view.findViewById(R.id.tv_main1_seckil_minutes);
        tv_main1_seckil_second = (TextView) view.findViewById(R.id.tv_main1_seckil_second);
        tv_main1_seckill_timenotes = (TextView) view.findViewById(R.id.tv_main1_seckill_timenotes);
        nowHour =  Integer.valueOf(simpleDateFormatHour.format(new Date()));
        if (nowHour < Constants.SECKILLSTART || nowHour > Constants.SECKILLEND - 1) {
            tv_main1_seckill_timenotes.setText("距下场开始");
        }else {
            tv_main1_seckill_timenotes.setText("距本场结束");
        }

        ll_main1_banner = (LinearLayout) view.findViewById(R.id.ll_main1_banner);
        btn_main1_coupon = (Button) view.findViewById(R.id.btn_main1_coupon);
        pb_main1_coupon = (ProgressBar) view.findViewById(R.id.pb_main1_coupon);
        btn_main1_coupon.setOnClickListener(this);

        //获取抢卷信息
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))) {

            if (nowHour < Constants.SECKILLSTART) {
                btn_main1_coupon.setText("试手气");
                btn_main1_coupon.setEnabled(false);
                pb_main1_coupon.setProgress(0);
                tv_main1_coupon_percent.setText("已抢0%");
            }else if (nowHour >= Constants.SECKILLEND) {
                btn_main1_coupon.setText("已结束");
                btn_main1_coupon.setEnabled(false);
                pb_main1_coupon.setProgress(100);
                tv_main1_coupon_percent.setText("已抢100%");

            } else if (nowHour < Constants.SECKILLMIDDLE) {
                getUserActivityInfoAM();
            }else {
                getUserActivityInfoPM();
            }
        } else {

            //未登录状态
            //1.00:00-09:59。试手气，按钮为灰色不可点击，抢卷比例为0.
            if (nowHour < Constants.SECKILLSTART) {
                btn_main1_coupon.setText("试手气");
                btn_main1_coupon.setEnabled(false);
                pb_main1_coupon.setProgress(0);
                tv_main1_coupon_percent.setText("已抢0%");
            }else if (nowHour > Constants.SECKILLMIDDLE && nowHour < Constants.SECKILLEND) {
                //2.10:00-18:00。试手气，按钮为红色，点击跳转至登录界面，抢卷比例为0.
                btn_main1_coupon.setText("试手气");
                btn_main1_coupon.setEnabled(true);
                pb_main1_coupon.setProgress(0);
                tv_main1_coupon_percent.setText("已抢0%");

            }else {
                //3.18:01以后，已结束，按钮为灰色，不可点击，抢卷比例100%
                btn_main1_coupon.setText("已结束");
                btn_main1_coupon.setEnabled(false);
                pb_main1_coupon.setProgress(100);
                tv_main1_coupon_percent.setText("已抢100%");
            }


        }



        //获取banner的广告栏
        vp_main1_banner = (ViewPager) view.findViewById(R.id.vp_main1_banner);
        vp_main1_banner.addOnPageChangeListener(this);
        getBannerInfo();


        //设置badgeview
        badgeView = new BadgeView(mContext);
        rl_main1_message = (RelativeLayout) view.findViewById(R.id.rl_main1_message);
        rl_main1_message.setOnClickListener(this);
        badgeView.setTargetView(rl_main1_message);
        badgeView.setTextColor(getResources().getColor(R.color.red));
        badgeView.setBackground(10,getResources().getColor(R.color.white));
        badgeView.setTextSize(8);



        //初始化信息

        getAppInitState();

        return view;
    }






    public void getAppInitState() {



        //构造传输参数
        final Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",String.valueOf(new Date().getTime()));

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.AppInitState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    listIndexPageModelEntities = new Gson().fromJson(jsonObject.getJSONArray("indexPageModel").toString(), new TypeToken<List<IndexPageModelEntity>>() {}.getType());
                    SharedPreferencesUtils.putString(HttpActions.AppInitState,jsonObject.optString("indexPageModel"));

                    if (listIndexPageModelEntities == null || listIndexPageModelEntities.isEmpty()) {
                        listIndexPageModelEntities = new ArrayList<IndexPageModelEntity>();
                    }
                    mMain1BannerPagerAdapter = new AdapterFragment1Grid(mContext,listIndexPageModelEntities);
                    mgv_main1.setAdapter(mMain1BannerPagerAdapter);


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                listIndexPageModelEntities = new Gson().fromJson(SharedPreferencesUtils.getString(HttpActions.AppInitState), new TypeToken<List<IndexPageModelEntity>>() {}.getType());
                if (listIndexPageModelEntities == null || listIndexPageModelEntities.isEmpty()) {
                    listIndexPageModelEntities = new ArrayList<IndexPageModelEntity>();
                }
                mMain1BannerPagerAdapter = new AdapterFragment1Grid(mContext,listIndexPageModelEntities);
                mgv_main1.setAdapter(mMain1BannerPagerAdapter);
            }
        });


    }




    @Override
    public void onResume() {
        super.onResume();
        //获取消息信息
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))) {
            getMessage();
        }

    }

    @Override
    public void onClick(View v) {

        Intent intent = null;

        switch (v.getId()) {

//            //钱包
//            case R.id.ll_main1_grid_1_1:
//
//
//                if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
//
//                    intent = new Intent(mContext,CashierActivity.class);
//                    startActivity(intent);
//                } else {
//                    getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
//                    getActivity().overridePendingTransition(R.anim.activity_open,0);
//                }
//
//
//                break;
//
//            //办理会员
//            case R.id.ll_main1_grid_1_2:
//
//
//                if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
//                    getVipInfo();
//                } else {
//                    getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
//                    getActivity().overridePendingTransition(R.anim.activity_open,0);
//                }
//
//
//
//                break;
//
//            //银联支付
//            case R.id.ll_main1_grid_2_1:
//
//                if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
//                    startActivity(CashierUnionOnlineActivity.class);
//                } else {
//                    getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
//                    getActivity().overridePendingTransition(R.anim.activity_open,0);
//                }
//                break;
//
//            //我要贷款
//            case R.id.ll_main1_grid_2_2:
//
//                if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
//                    intent = new Intent(mContext, ShowH5WithTitleActivity.class);
//                    intent.putExtra("url","http://wap.life.hzjieniu.com/service/baike.htm");
//                    intent.putExtra("title","用卡百科");
//                    startActivity(intent);
//                } else {
//                    getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
//                    getActivity().overridePendingTransition(R.anim.activity_open,0);
//                }
//
//
//                break;

            //消息通知
            case R.id.rl_main1_message:

                if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){
                    intent = new Intent(mContext, MessageListActivity.class);
                    intent.putExtra("systemUnRead",systemUnRead);
                    intent.putExtra("systemLastMsgTime",systemLastMsgTime);
                    intent.putExtra("systemLastMsg",systemLastMsg);
                    intent.putExtra("activeUnRead",activeUnRead);
                    intent.putExtra("activeLastMsgTime",activeLastMsgTime);
                    intent.putExtra("activeLastMsg",activeLastMsg);
                    startActivity(intent);
                } else {
                    getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
                    getActivity().overridePendingTransition(R.anim.activity_open,0);
                }

                break;

            //抢卷
            case R.id.btn_main1_coupon:


                if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsUser.userToken))){


                    nowHour = Integer.valueOf(simpleDateFormatHour.format(new Date()));

                    if (nowHour >= Constants.SECKILLSTART && nowHour < Constants.SECKILLMIDDLE) {
                        tryLuck("TheirLuckAm");
                    }else if (nowHour >= Constants.SECKILLMIDDLE && nowHour < Constants.SECKILLEND) {
                        tryLuck("TheirLuckPm");
                    }else {
                        ToastUtils.showToast("还未到抢卷时间！");
                    }
                } else {
                    getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
                    getActivity().overridePendingTransition(R.anim.activity_open,0);
                }




                break;
            default:
                AlertDialogUtils.showAlertDialog(mContext,getResources().getString(R.string.building));

        }

    }


    //试手气
    private void tryLuck(String ActivityCode) {


        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("ActivityCode",ActivityCode);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserTryTheirLuck, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                //1已经领取  0谢谢参与
                    if (jsonObject.optString("theirluckStatus").equals("0")) {
                        btn_main1_coupon.setText("谢谢参与");
                        btn_main1_coupon.setEnabled(false);

                        View toastRoot = LayoutInflater.from(mContext).inflate(R.layout.dialog_main1_seckill_fail, null);
                        //Toast的初始化
                        Toast toastStart = new Toast(mContext);
                        //获取屏幕高度
                        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
                        int height = wm.getDefaultDisplay().getHeight();
                        //Toast的Y坐标是屏幕高度的1/3，不会出现不适配的问题
                        toastStart.setGravity(Gravity.TOP, 0, height / 3);
                        toastStart.setDuration(Toast.LENGTH_SHORT);
                        toastStart.setView(toastRoot);
                        toastStart.show();


                    }else {
                        btn_main1_coupon.setText("已领取");
                        btn_main1_coupon.setEnabled(false);
                        final SecKillSuccessDialog dialog = new SecKillSuccessDialog(mContext);
                        dialog.show();
                        dialog.setCanceledOnTouchOutside(false);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }


    /**
     *
     */
    public void getVipInfo() {

        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",timestamp);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserVipInfo, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    Intent intent = new Intent(mContext,MembershipCenterActivity.class);
                    intent.putExtra("vipRate",jsonObject.optString("vipRate"));
                    intent.putExtra("birthdayCount",jsonObject.optString("birthdayCount"));
                    intent.putExtra("isVip",jsonObject.optString("isVip"));
                    intent.putExtra("expireDay",jsonObject.optString("expireDay"));
                    intent.putExtra("meal",jsonObject.optString("meal"));
                    startActivity(intent);


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentItem = position;

        //Banner的指示器
        for (int i = 0; i < bannersList.size() ; i++) {
            if (i == (currentItem) % bannersList.size()) {
                ll_main1_banner.getChildAt(i).setSelected(true);
            } else {
                ll_main1_banner.getChildAt(i).setSelected(false);
            }
        }


    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //获取抢卷活动信息AM
    public void getUserActivityInfoAM() {


        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        //TheirLuckAm:试手气抢卷-上午场   TheirLuckPm:试手气抢卷-下午场
        map.put("ActivityCode","TheirLuckAm");

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserActivityInfo, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    //中奖率
                    tv_main1_coupon_percent.setText("已抢"+(jsonObject.optInt("activitySendPrice")*100/jsonObject.optInt("activityPrice"))+"%");
                   pb_main1_coupon.setProgress(jsonObject.optInt("activitySendPrice")*100/jsonObject.optInt("activityPrice"));
                    //是否可以抢卷

                    if ((jsonObject.optInt("activitySendPrice")/jsonObject.optInt("activityPrice")) == 1) {
                        btn_main1_coupon.setText("已结束");
                        btn_main1_coupon.setEnabled(false);
                    }else {
                        if (jsonObject.optInt("theirluck") == 0 && nowHour >= Constants.SECKILLSTART && nowHour < Constants.SECKILLMIDDLE) {
                            btn_main1_coupon.setText("试手气");
                            btn_main1_coupon.setEnabled(true);
                        }else if (jsonObject.optInt("theirluck") == 1) {
                            btn_main1_coupon.setText("已领取");
                            btn_main1_coupon.setEnabled(false);
                        }else if (jsonObject.optInt("theirluck") == 2) {
                            btn_main1_coupon.setText("谢谢参与");
                            btn_main1_coupon.setEnabled(false);
                        }else {
                            btn_main1_coupon.setText("试手气");
                            btn_main1_coupon.setEnabled(false);
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

            }
        });

    }






    //获取抢卷活动信息PM
    public void getUserActivityInfoPM() {


        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        //TheirLuckAm:试手气抢卷-上午场   TheirLuckPm:试手气抢卷-下午场
        map.put("ActivityCode","TheirLuckPm");

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserActivityInfo, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    //中奖率
                    tv_main1_coupon_percent.setText("已抢"+(jsonObject.optInt("activitySendPrice")/jsonObject.optInt("activityPrice"))/100+"%");
                    pb_main1_coupon.setProgress(jsonObject.optInt("activitySendPrice")/jsonObject.optInt("activityPrice"));

                    if ((jsonObject.optInt("activitySendPrice")/jsonObject.optInt("activityPrice")) == 1) {
                        btn_main1_coupon.setText("已结束");
                        btn_main1_coupon.setEnabled(false);
                    }else {
                        //是否可以抢卷
                        if (jsonObject.optInt("theirluck") == 0 && nowHour >= Constants.SECKILLMIDDLE && nowHour < Constants.SECKILLEND) {
                            btn_main1_coupon.setText("试手气");
                            btn_main1_coupon.setEnabled(true);
                        }else if (jsonObject.optInt("theirluck") == 1) {
                            btn_main1_coupon.setText("已领取");
                            btn_main1_coupon.setEnabled(false);
                        }else if (jsonObject.optInt("theirluck") == 2) {
                            btn_main1_coupon.setText("谢谢参与");
                            btn_main1_coupon.setEnabled(false);
                        }else {
                            btn_main1_coupon.setText("试手气");
                            btn_main1_coupon.setEnabled(false);
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

            }
        });

    }


    //获取消息
    public void getMessage() {



        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",timestamp);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserNoticeMsg, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if ((jsonObject.optInt("systemUnRead") + jsonObject.optInt("activeUnRead") == 0)) {
                        badgeView.setVisibility(View.GONE);
                    }else {
                        badgeView.setBadgeCount(jsonObject.optInt("systemUnRead") + jsonObject.optInt("activeUnRead"));
                    }
                     systemUnRead = jsonObject.optInt("systemUnRead");
                     systemLastMsgTime = jsonObject.optString("systemLastMsgTime");
                     systemLastMsg = jsonObject.optString("systemLastMsg");
                     activeUnRead = jsonObject.optInt("activeUnRead");
                     activeLastMsgTime = jsonObject.optString("activeLastMsgTime");
                     activeLastMsg = jsonObject.optString("activeLastMsg");


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });


    }

    //获取banner广告栏
    public void getBannerInfo() {



        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("adArea","A1002");
        map.put("adSize","10");

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.AdInfoState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    bannersList = new Gson().fromJson(jsonObject.getJSONArray("adInfoList").toString(), new TypeToken<List<AdvertisementEntity>>() {}.getType());

                    //设置banner的指示器
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(4, 4, 4, 4);
                    ll_main1_banner.removeAllViews();
                    for (int i = 0; i < bannersList.size(); i++) {
                        ImageView imageView = new ImageView(mContext);
                        imageView.setLayoutParams(layoutParams);
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageResource(R.drawable.select_dot);
                        ll_main1_banner.addView(imageView);
                    }
                    bannerPagerAdapter = new Main1BannerPagerAdapter(mContext,bannersList);
                    vp_main1_banner.setAdapter(bannerPagerAdapter);
                    vp_main1_banner.setCurrentItem(bannersList.size()*1000);
                    currentItem = bannersList.size()*1000;

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
            }
        });

    }


    //用来完成图片切换的任务
    private class ViewPagerTask implements Runnable{

        public void run() {
            //实现我们的操作
            //改变当前页面
            currentItem = currentItem + 1;
            //Handler来实现图片切换
            handler.sendEmptyMessage(1);
        }
    }


    //用来完成倒计时的任务
    private class SecKilTask implements Runnable{

        public void run() {

            handler.sendEmptyMessage(2);
        }
    }





    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            //设定viewPager当前页面

            if (msg.what == 1) {
                vp_main1_banner.setCurrentItem(currentItem);
            }else if (msg.what == 2){
                int nowHour  = Integer.valueOf(simpleDateFormatHour.format(new Date()));
                int nowMinute  = Integer.valueOf(simpleDateFormatMinute.format(new Date()));
                int nowSecond  = Integer.valueOf(simpleDateFormatSecond.format(new Date()));
                String now = simpleDateFormat.format(new Date());
                String[] splitDate = now.split(":");

                if ((nowHour == Constants.SECKILLSTART || nowHour == Constants.SECKILLMIDDLE) && nowMinute == 0 && nowSecond < 2) {
                    btn_main1_coupon.setEnabled(true);
                    tv_main1_seckill_timenotes.setText("距本场结束");
                }



                if (nowHour < Constants.SECKILLSTART) {
                    setSecKilTime((Constants.SECKILLSTART -1-Integer.valueOf(splitDate[0])),(59 -Integer.valueOf(splitDate[1])),(59 -Integer.valueOf(splitDate[2])));
                }else if (nowHour >= Constants.SECKILLEND) {
                    tv_main1_seckil_hour.setText("00");
                    tv_main1_seckil_minutes.setText("00");
                    tv_main1_seckil_second.setText("00");
                }else if (nowHour >= Constants.SECKILLSTART && nowHour <Constants.SECKILLMIDDLE){
                    setSecKilTime((Constants.SECKILLMIDDLE -1 -Integer.valueOf(splitDate[0])),(59 -Integer.valueOf(splitDate[1])),(59 -Integer.valueOf(splitDate[2])));
                }else if (nowHour >= Constants.SECKILLMIDDLE && nowHour < Constants.SECKILLEND){
                    setSecKilTime((Constants.SECKILLEND -1 -Integer.valueOf(splitDate[0])),(59 -Integer.valueOf(splitDate[1])),(59 -Integer.valueOf(splitDate[2])));
                }

            }
        }
    };


    private void setSecKilTime(int hour, int minute, int second) {



        if (hour < 10) {
            tv_main1_seckil_hour.setText("0" + hour);

        }else {
            tv_main1_seckil_hour.setText(hour + "");

        }

        if (minute < 10) {
            tv_main1_seckil_minutes.setText("0" + minute);

        }else {
            tv_main1_seckil_minutes.setText(minute + "");

        }

        if (second < 10) {
            tv_main1_seckil_second.setText("0" + second);

        }else {
            tv_main1_seckil_second.setText(second + "");

        }

    }




}